$(function () {
    var config = {
        clientele: '/clientele/queryPinyin?size=10000', // 客户
    };
    $.when(parent.window.getDataByUrl(config.clientele, 'clientelePinyin'))
        .then(function (clients) {
            clients.map(function (item) {
                $('select[name=clienteleId]').append('<option data-code="' + item.unitCode + '" value="' + item.id + '">' + item.comName + '/'
                    + item.person + '/' + item.phone + '/' + item.unitCode + '</option>')
            });
            validate();
        })
        .fail(function (e) {
            console.log(e);
        });


    function validate() {
        $('#form-replace')
            .find('[name="clienteleId"]')
            .selectpicker({
                liveSearch: true,
            })
            .change(function (e) {
                /* Revalidate the color when it is changed */
                $('#form-replace').formValidation('revalidateField', 'clienteleId');
            })
            .end()
            .find('[name="comName"]')
            .change(function (e) {
                /* Revalidate the color when it is changed */
                $('#form-replace').formValidation('revalidateField', 'comName');
            })
            .end()
            .formValidation('destroy').formValidation($.extend({}, VALIDATION_SETTING, {
            fields: {
                clienteleId: {
                    row: '.col-sm-6',
                    validators: {
                        notEmpty: {
                            message: '客户必选'
                        },
                    }
                },

                unitCode: {
                    row: '.col-sm-6',
                    validators: {
                        notEmpty: {}
                    }
                }
            }
        }))
            .off('success.form.fv').on('success.form.fv', function (e) {
            e.preventDefault();
            var form = parseSearch($(e.target).serialize());
            var $text = $('[name=clienteleId] option:selected').text().split("/");
            form['clientelePhone'] = $text[2];
            if (form['unitCode'].length != 18) {
                return alert('请输入18位统一信用代码!');
            }
            form['_unitCode'] = $('[name=clienteleId] option:selected').data('code');
            $.get("/clientele/replace/" + form.unitCode + '/' + form.clienteleId + '/' + form['_unitCode'],  function (xhr, data) {
                if (xhr.code == 200) {
                    fnSuccess('替换成功!');
                    window.location = './index.html';

                } else {
                    alert(xhr.error || xhr.msg);
                }
            });
        });
    }
})